<?php
App::uses('AppController', 'Controller');
/**
 * Items Controller
 *
 * @property Item $Item
 */
class ItemsController extends AppController {
	var $components = array('RequestHandler', 'Session', 'Cookie');
	/**
	 * index method
	 *
	 * @return void
	 */
	public function index() {
		$this -> Item -> recursive = 0;
		// $this->set ( 'items', $this->paginate
		// ("Items",null,array("conditions"=>array("Items.online"=>"yes"))) );
		$this -> set('items', $this -> paginate("Item"));
		$this -> set('categories', $this -> Category -> find('all'));

		// $this->set('images', $this->Item->Image->find('all'));
		// $this->set('images', $this->paginate('Image'));
		// $image = $this->Item->data['Item']['image_id'];
		// $imageName = $image['Image']['name'];

		$this -> pageTitle = '- Items';
	}
	
	public function indexdata() {	

        $this->autoRender = false;  
		$output = $this->Item->GetData();	
		echo json_encode($output);
		
	}

	public function publicIndex() {
		$this -> Item -> recursive = 0;
		// $this->set ( 'items', $this->paginate
		// ("Items",null,array("conditions"=>array("Items.online"=>"yes"))) );
		$condition = array('Item.online' => 'yes', 'Item.item_status_id' => 1);
		$this -> set('items', $this -> paginate("Item", $condition));
		$this -> set('categories', $this -> Category -> find('all'));

		// $this->set('images', $this->Item->Image->find('all'));
		// $this->set('images', $this->paginate('Image'));
		// $image = $this->Item->data['Item']['image_id'];
		// $imageName = $image['Image']['name'];

		$this -> pageTitle = '| Online Store';
	}

	/**
	 * view method
	 *
	 * @throws NotFoundException
	 * @param string $id
	 * @return void
	 */
	public function view($id = null) {
		if (!$this -> Item -> exists($id)) {
			throw new NotFoundException(__('Invalid item'));
		}

		/**
		 * markdown*
		 */
		//$markdown_price = '';
		//$options = array('conditions' => array('Item.' . $this -> Item -> primaryKey => $id));
		//$this -> set('item', $this -> Item -> find('first', $options));
		// $this->set('image', $this->Image->find('all'));

		//$this -> loadModel('Markdown');
		//$this -> set('markdown_price', $this -> Markdown -> find('first', array('conditions' => array('Markdown.item_id' => $id), 'order' => array('Markdown.markdown_date' => 'Desc'), 'fields' => array('Markdown.markdown_price'))));
		/* Markdown */

		$options = array('conditions' => array('Item.' . $this -> Item -> primaryKey => $id));
		$this -> set('item', $this -> Item -> find('first', $options));
		// $this->set('image', $this->Image->find('all'));
		$this -> set('images', $this -> Item -> find('all', array('conditions' => array('Item.' . $this -> Item -> primaryKey => $id))));
	}

	public function view_item($id) {
		// view
	}

	/**
	 * add method
	 *
	 * @return void
	 */
	public function add() {
		if ($this -> request -> is('post')) {
			/*
			 * $this->Item->create (); if ($this->Item->save (
			 * $this->request->data )) { $this->Session->setFlash ( __ ( 'The
			 * item has been saved' ) ); $this->redirect ( array ( 'action' =>
			 * 'index' ) ); } else { $this->Session->setFlash ( __ ( 'The item
			 * could not be saved. Please, try again.' ) ); }
			 */
			$this -> Item -> set($this -> data);
			$this -> Item -> Image -> set($this -> data);
			
			
			
			foreach ($this->request->data ['Image'] as $key => $value) {
				if( isset($this -> request -> data['Image'][$key]['name']['tmp_name']))
				{
					if (is_uploaded_file($this -> request -> data['Image'][$key]['name']['tmp_name']) && !empty($this -> request -> data['Image'][$key]['name']['tmp_name'])) {
						$path_info = pathinfo($this -> request -> data['Image'][$key]['name']['name']);
						chmod($this -> request -> data['Image'][$key]['name']['tmp_name'], 0644);
						$photo = time() . mt_rand() . "." . $path_info['extension'];
						$fullpath = WWW_ROOT . "img" . DS . IMG_DIR;
						$res1 = is_dir($fullpath);
						if ($res1 != 1) {
							$res2 = mkdir($fullpath, 0777, true);
						}
						move_uploaded_file($this -> request -> data['Image'][$key]['name']['tmp_name'], $fullpath . DS . $photo);
						$this -> request -> data['Image'][$key]['name'] = $photo;
					} else {
						unset($this -> request -> data['Image'][$key]['name']);
					}
				}
			}
			if ($this -> data['Item']['location'] == 'On Display') {
				$this -> request -> data['Item']['on_display_date'] = date("Y-m-d");
			}

			// debug($this->data);
			// die();
			if( isset($photo))
			$this -> request -> data['Item']['photo'] = $photo;
			
			$this -> data = Set::filter($this -> data);
			$result = $this -> Item -> saveAll($this -> request -> data);
			//$this->Item->saveAll ( $this->request->data ); before merging
			$this -> Session -> setFlash(__('Added successful'));

			$msg = array(__('The Item has been saved'), __('The Item could not be saved. Please, try again.'));

			// if ajax request, then back to json data
			if ($this -> request -> is("ajax")) {
				header("Pragma: no-cache");
				header("Cache-Control: no-store, no-cache, max-age=0, must-revalidate");
				header('Content-Type: text/x-json');
				header('Content-type: application/json');
				$itemlist = array();
				$status = false;

				$item_all = $this -> Item -> find("all");

				if (!empty($item_all)) {
					foreach ($item_all as $v) {$itemlist[] = $v["Item"];
					}
				}

				$status = true;

				$data = array("status" => $status, "message" => $status ? $msg[0] : $msg[1], "itemlist" => $itemlist);

				echo json_encode($data);
				die();

			}

			$this -> redirect('index');
		}
		$brands = $this -> Item -> Brand -> find('list', array('order' => 'Brand.name asc'));
		$colors = $this -> Item -> Color -> find('list', array('order' => 'Color.name asc'));
		$conditions = $this -> Item -> Condition -> find('list', array('order' => 'Condition.name asc'));
		$sizes = $this -> Item -> Size -> find('list', array('order' => 'Size.name asc'));
		$categories = $this -> Item -> Category -> find('list', array('order' => 'Category.name asc'));
		$itemStatuses = $this -> Item -> ItemStatus -> find('list', array('order' => 'ItemStatus.name asc'));
		$images = $this -> Item -> Image -> find('list');
		$this -> set(compact('brands', 'colors', 'conditions', 'sizes', 'categories', 'itemStatuses', 'images'));
	}

	/**
	 * edit method
	 *
	 * @throws NotFoundException
	 * @param string $id
	 * @return void
	 */
	public function edit($id = null) {
		if (!$this -> Item -> exists($id)) {
			throw new NotFoundException(__('Invalid item'));
		}
		if ($this -> request -> is('post') || $this -> request -> is('put')) {


			// $conditions = array('Image.item_id' => $id);
			// $results = $this->Image->find('first', array('conditions' =>
			// $conditions));

			// $results = $this->Item->Image->find('first', array('conditions'
			// => $conditions), array('fields' => 'name'));
			// $results = $this->Item->Image->find('first', array('conditions'
			// => $conditions));
			// $this->Item->set('image_name', $results);

			$checkItem = $this -> Item -> find('first', array('conditions' => array('Item.id' => $id)));
			if (($this -> data['Item']['location'] == 'On Display') and (!$checkItem['Item']['on_display_date'])) {
				$this -> Item -> set('on_display_date', date("Y-m-d"));
			}

			if ($this -> Item -> save($this -> request -> data)) {
				$this -> Session -> setFlash(__('The item has been saved'));
				$this -> redirect(array('action' => 'index'));
			} else {
				$this -> Session -> setFlash(__('The item could not be saved. Please, try again.'));
			}
		} else {
			$options = array('conditions' => array('Item.' . $this -> Item -> primaryKey => $id));
			$this -> request -> data = $this -> Item -> find('first', $options);
		}
		$brands = $this -> Item -> Brand -> find('list');
		$colors = $this -> Item -> Color -> find('list');
		$conditions = $this -> Item -> Condition -> find('list');
		$sizes = $this -> Item -> Size -> find('list');
		$categories = $this -> Item -> Category -> find('list');
		$itemStatuses = $this -> Item -> ItemStatus -> find('list');

		/*
		 * $conditions_images = array('Image.item_id' => $id);
		 * $this->set('images', $this->Item->Image->find('list',
		 * array('conditions' => $conditions_images)));
		 */
		$this -> set(compact('brands', 'colors', 'conditions', 'sizes', 'categories', 'itemStatuses'));

		$options = array('conditions' => array('Item.' . $this -> Item -> primaryKey => $id));
		$this -> set('item', $this -> Item -> find('first', $options));

		//debug($item);
		// $this->set('image', $this->Image->find('all'));

	}

	/**
	 * delete method
	 *
	 * @throws NotFoundException
	 * @throws MethodNotAllowedException
	 * @param string $id
	 * @return void
	 */
	public function delete($id = null) {
		$this -> Item -> id = $id;
		if (!$this -> Item -> exists()) {
			throw new NotFoundException(__('Invalid item'));
		}
		$this -> request -> onlyAllow('post', 'delete');

		$photos = $this -> Item -> Image -> find('all', array('conditions' => array('Image.item_id' => $id)));
		foreach ($photos as $result) {
			$photoName = $result['Image']['name'];
			$fullpath = WWW_ROOT . "img" . DS . IMG_DIR;
			unlink($fullpath . DS . $photoName);
			$this -> Item -> Image -> delete($result['Image']['id']);
		}
		$this -> Item -> delete();
		$this -> Session -> setFlash(__('Item # %s deleted', $id));
		$this -> redirect('index');
	}

	// ----------------------------------------------------------------------

	public function beforeFilter() {
		parent::beforeFilter();

		$this -> Auth -> autoRedirect = false;

		$this -> Auth -> allow('index', 'publicIndex', 'view', 'search');
		// $this->Auth->allow('view');

		$this -> loadModel('Category');
	}

	// ----------------------------------------------------------------------
	public function search() {
		// $this->set('results',$this->Customer->search($this->data['Customer']['q']));
		if (isset($_REQUEST["term"])) {
			$keyword = h($_REQUEST["term"]);
		} else {
			$keyword = $this->request->data['Item']['keywords'];
		}
		// get keyword from querystring
		// used simpme or condition with singe value checking
		// replace ModelName with actual name of your Appmodel

		// $this->Session->setFlash($keyword);
		$search_key = "%$keyword%";
		$conditions = array("ItemStatus.id" => array(1, 3), 'OR' => array('Item.id LIKE' => $search_key, 'Item.name LIKE' => $search_key, 'Item.original_price LIKE' => $search_key, 'Brand.name LIKE' => $search_key, 'Category.name LIKE' => $search_key, 'Color.name LIKE' => $search_key));

		$this -> set('isFound', $this -> Item -> find('count', array('conditions' => $conditions)));

		$this -> set('list', $this -> Item -> find('all', array('conditions' => $conditions, "order" => array("Item.name" => "ASC"))));
		
		// $this->set('images', $this->Item->Image->find('all'));
		// $this->set('images', $this->paginate('Image'));
		// $image = $this->Item->data['Item']['image_id'];
		// $imageName = $image['Image']['name'];

		$this -> pageTitle = '| Online Store';
	}

	/*start Markdown code*/
	public function price() {
		$getExpireDate = date("Y-m-d", strtotime("-64 day"));
		//$conditions = array('Item.location' => 'On Display', 'Item.online' => 'Yes', 'Item.is_discounted' => 'No', 'Item.on_display_date <= ' => $getExpireDate);
		$conditions = array('Item.location' => 'On Display', 'Item.item_status_id' => 1, 'Item.on_display_date <= ' => $getExpireDate);
		$this -> paginate = array('conditions' => $conditions, "order" => array("Item.on_display_date" => "ASC"));
		$this -> set('items', $this -> paginate());
	}

	/*end*/
}
